import functools
import json
import os
import time

from absl import app, flags
from tornado.ioloop import IOLoop

from coin.exchange.prex_futures.rest.api import PrexFuturesRestApi
from coin.exchange.base.kr_rest.auth_base import AuthKey


FLAGS = flags.FLAGS


USE_ASYNC = True


def print_msg(update):
  try:
    msg = update.msg
  except Exception:
    msg = update

  print(json.dumps(msg, indent=2, default=str))


def run_func(func, *args, **kwargs):
  task = functools.partial(func, *args, **kwargs)
  if USE_ASYNC:
    update = IOLoop.current().run_sync(task)
  else:
    update = task()
  return update


def main(_):
  key_file = os.path.expanduser(FLAGS.key_file)
  config = AuthKey.from_config_filename(key_file)
  client = PrexFuturesRestApi(config.access_key, config.secret_key, FLAGS.url)

  count = 0
  while count <= 10:
    try:
      update = run_func(client.cancel_all)
      break
    except Exception:
      import traceback
      traceback.print_exc()
      count += 1
  print_msg(update)


if __name__ == '__main__':
  flags.DEFINE_string('key_file', None, "trade key file path")
  flags.DEFINE_string('url', None, "exchange server url")
  app.run(main)
